package org.xshop.service.impl;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.xshop.mapper.TGoodsLimitMapper;
import org.xshop.model.TGoods;
import org.xshop.model.TGoodsLimit;
import org.xshop.model.TGoodsPromotion;
import org.xshop.model.TMemberCollection;
import org.xshop.service.ITGoodsLimitService;
import org.xshop.service.ITMemberCollectionService;

import com.weibo.api.motan.config.springsupport.annotation.MotanService;

import top.ibase4j.core.base.BaseServiceImpl;
import top.ibase4j.core.support.Pagination;
import top.ibase4j.core.util.DateUtil;

/**
 * <p>
 * 商品限购 服务实现类
 * </p>
 *
 * @author ShenHuaJie
 * @since 2017-03-26
 */
@MotanService(interfaceClass = ITGoodsLimitService.class)
@CacheConfig(cacheNames = "goodsLimit")
public class GoodsLimitService extends BaseServiceImpl<TGoodsLimit, TGoodsLimitMapper> implements ITGoodsLimitService {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ITMemberCollectionService memberCollectionService;

    @Override
    public Pagination<TGoodsLimit> getAllGoods(Map<String, Object> param) {
        param.put("online", 1);// 在线 未过期
        param.put("enable", "1");

        Pagination<TGoodsLimit> page = query(param);
        Object member = param.get("memberId");
        if (page != null) {
            for (TGoodsLimit goodsLimit : page.getRecords()) {
                TGoods goods = goodsService.queryById(goodsLimit.getGoodsId());
                if (goods.getIsPromotion() == 1) {
                    TGoodsPromotion promotion = goods.getPromotion();
                    if (promotion != null) {
                        Date now = DateUtil.stringToDate(DateUtil.getDate());
                        if (!promotion.getStartTime().after(now) && !promotion.getEndTime().before(now)) {
                            goods.setSalePrice(promotion.getPrice());
                        }
                    }
                }
                if (member != null) {
                    Long memberId = Long.parseLong(member.toString());
                    // 商品收藏
                    TMemberCollection memberCollection = new TMemberCollection();
                    memberCollection.setMemberId(memberId);
                    memberCollection.setCollectionId(goods.getId());
                    memberCollection = memberCollectionService.selectOne(memberCollection);
                    if (memberCollection == null) {
                        // 未收藏
                        goods.setCollect(0);
                    } else {
                        // 已收藏
                        goods.setCollect(1);
                    }
                }
                goodsLimit.setGoods(goods);
            }
        }
        return page;
    }

}